package com.zlzlib.libdialog.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zlz on 2017/9/21.
 */

public abstract class NormalAdapter<T> extends BaseAdapter {
    protected Context context;
    protected List<T> data;
    protected final int itemLayoutId;

    public NormalAdapter(Context context, int itemLayoutId) {
        this.context = context;
        this.itemLayoutId = itemLayoutId;
        data = new ArrayList<>();
    }

    public NormalAdapter(Context context, int itemLayoutId, List<T> data) {
        this.context = context;
        this.itemLayoutId = itemLayoutId;
        this.data = data;
    }

    public void remove(T b) {
        data.remove(b);
        notifyDataSetChanged();
    }

    public void add(T b) {
        data.add(b);
        notifyDataSetChanged();
    }

    public void setData(List<T> data) {
        if (data == null)
            return;
        this.data = data;
        notifyDataSetChanged();
    }

    public List<T> getData() {
        return data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = LayoutInflater.from(context).inflate(itemLayoutId, null);
        convert(convertView, data, position);
        return convertView;
    }

    protected abstract void convert(View convertView, List<T> data, int position);

    public static <T extends View> T get(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }
}
